package com.loong.musicdemo.ui.account.MyCenter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.loong.musicdemo.R;
import com.loong.musicdemo.adapter.PlayListAdapter;
import com.loong.musicdemo.model.SongList;
import com.loong.musicdemo.util.dataDeal.PlayListDeal;

import java.util.ArrayList;
import java.util.List;

public class MyCenter extends Fragment {
    private RecyclerView myPlayList;//我的歌单
    private ProgressBar loading;//刷新中
    private final List<SongList> songList = new ArrayList<>();
    private PlayListAdapter adapter;

    public MyCenter() {

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_my_center, container, false);
        myPlayList = root.findViewById(R.id.my_play_list);
        loading = root.findViewById(R.id.loading);
        LinearLayoutManager layoutManager = new LinearLayoutManager(requireContext());
        myPlayList.setLayoutManager(layoutManager);
        //适配器
        adapter = new PlayListAdapter(songList);
        myPlayList.setAdapter(adapter);
        initPlayList();
        return root;
    }

    @SuppressLint("StaticFieldLeak")
    class GetUserPlayList extends AsyncTask<Void, Void, List<SongList>> {
        @Override
        protected void onProgressUpdate(Void... values) {//进度刷新
            super.onProgressUpdate(values);
            myPlayList.setVisibility(View.GONE);//设置 不可见
            loading.setVisibility(View.VISIBLE);
        }

        @Override
        protected List<SongList> doInBackground(Void... voids) {
            SharedPreferences userInfo = requireActivity().getSharedPreferences("userInfo", Context.MODE_PRIVATE);
            String userId = userInfo.getString("userId", null);
            return PlayListDeal.getUserAllPlayListInfo(userId);
        }

        @Override
        protected void onPostExecute(List<SongList> songLists) {//请求执行完成
            super.onPostExecute(songLists);
            //歌单列表
            if (isAdded()){
                songList.addAll(songLists);
                adapter.notifyDataSetChanged();
            }
            //将RecyclerView可见
            loading.setVisibility(View.GONE);//加载中不可见
            myPlayList.setVisibility(View.VISIBLE);
        }
    }


    /**
     * 获取
     */
    private void initPlayList() {
        new GetUserPlayList().execute();
    }
}
